<template>
  <Teleport to="body">
    <el-dialog v-model="appStore.showUpdatePasswordDialog" title="修改密码" :close-on-click-modal="false" :width="dialogWidth">
      <el-form :model="updatePwdForm" :rules="updatePwdRules" ref="updatePwdFormRef" :labelPosition>
        <el-form-item label="旧登录密码" prop="oldPassword">
          <el-input type="password" show-password v-model.trim="updatePwdForm.oldPassword" placeholder="请输入旧密码"></el-input>
        </el-form-item>
        <el-form-item label="新登录密码" prop="newPassword">
          <el-input type="password" show-password v-model.trim="updatePwdForm.newPassword" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="repeatPassword">
          <el-input type="password" show-password v-model.trim="updatePwdForm.repeatPassword" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        <div class="flex-center">
          <ep-button svg-icon="Close" type="info" @click="close">取消</ep-button>
          <ep-button svg-icon="Save" type="primary" @click="submit">提交</ep-button>
        </div>
      </el-form>
    </el-dialog>
  </Teleport>
</template>

<script setup lang="ts">
defineOptions({ name: 'UpdatePassword' })
import { UserRequest } from '@/api/system/user.request'
import { TipModal } from '@/utils'
import type { FormInstance, FormRules } from 'element-plus'

const appStore = useAppStore()
const labelPosition = computed(() => (appStore.isDesktop ? 'left' : 'top'))
const dialogWidth = computed(() => (appStore.isDesktop ? `500px` : `calc(100% - 32px)`))
const updatePwdFormRef = shallowRef<FormInstance>()
const updatePwdForm = ref({} as UserType.UpdatePwdDTO)
const loading = ref<boolean>(false)
const userStore = useUserStore()
const updatePwdRules: FormRules<UserType.UpdatePwdDTO> = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  repeatPassword: [{ required: true, message: '请再次输入新密码', trigger: 'blur' }],
}

function close() {
  if (loading.value) return TipModal.msgWarning('数据处理中，请勿退出')
  appStore.showUpdatePasswordDialog = false
}

async function submit() {
  try {
    await updatePwdFormRef.value?.validate()
    const errMsg = validateRequestBody()
    if (errMsg) return TipModal.msgError(errMsg)
    loading.value = true
    const updateDto = buildRequestBody()
    const actionMsg = await UserRequest.updatePassword(updateDto)
    TipModal.msgSuccess(actionMsg || '修改成功')
    setTimeout(() => TipModal.msgWarning(`即将跳转登录页面，请稍后`), 1000)
    setTimeout(() => userStore.logout(), 1500)
    setTimeout(() => window.location.reload(), 2000)
  } catch (error: any) {
    console.log('修改密码失败: ', error.message || error)
  } finally {
    loading.value = false
  }
}

function validateRequestBody(): string | undefined {
  const { oldPassword, newPassword, repeatPassword } = updatePwdForm.value
  if (newPassword !== repeatPassword) return `两次输入的新密码不一致`
  if (oldPassword === repeatPassword) return `新密码不可与旧密码一样`
}

function buildRequestBody() {
  const data = {} as UserType.UpdatePwdDTO
  data.oldPassword = updatePwdForm.value.oldPassword
  data.newPassword = updatePwdForm.value.newPassword
  data.repeatPassword = updatePwdForm.value.repeatPassword
  data.userId = userStore.user.id
  return data
}
</script>

<style lang="scss" scoped>
.el-button {
  width: 120px;
}
</style>
